//
//  SearchController.m
//  ShopDemo
//
//  Created by Sunshine on 2018/8/15.
//  Copyright © 2018年 飞扬的青春. All rights reserved.
//

#import "SearchController.h"
#import "SearchView.h"
#import "ShopDetailController.h"
#import "FirDetailController.h"
@interface SearchController ()<UICollectionViewDelegate,UICollectionViewDataSource,UICollectionViewDelegateFlowLayout>

@property(nonatomic,strong)UICollectionView *listCollectionview;
@property (strong, nonatomic) UIView *backHdview;
@property(nonatomic,strong)NSArray *contentArray;
@property(nonatomic,strong)SearchView *headerView;
@property(nonatomic,strong)UITextField *searchfield;
@property(nonatomic,strong)NSString *searchStr;
@property(nonatomic,assign)NSInteger index;
@property(nonatomic,assign)NSInteger page;
@property(nonatomic,strong)NSMutableArray *datasource;


@end

@implementation SearchController

-(NSMutableArray *)datasource{
    if (!_datasource) {
        _datasource = [NSMutableArray arrayWithCapacity:10];
    }
    return _datasource;
}


- (void)viewDidLoad {
    [super viewDidLoad];
    self.index = 1;
    self.page = 0;
    
    [self creatCollectionViewMethod];
    [self creatSearchHeaderView];
    NSString *urlstr = [NSString stringWithFormat:@"/dashop/dictionaries/app/list.do?BIANMA=SearchKey"];
    NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:urlstr];
    [self ContentDataMethodWithUrl:endstr];
    
    self.listCollectionview.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingBlock:^{
        if (self.page == 10 ) {
            self.index ++;
            NSString *urlstr = [NSString stringWithFormat:@"/dashop/goods/app/list.do?keywords=%@&CurrentPage=%ld",self
                                .searchStr,self.index];
            NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:urlstr];
            NSString  *newUrlString = [endstr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
            [self SearchShopMethodWithUrl:newUrlString];
        }else{
            [self.listCollectionview.mj_footer endRefreshingWithNoMoreData];
        }
    }];
    
    
}

-(void)ContentDataMethodWithUrl:(NSString *)url{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        self.contentArray = response;
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
            self.headerView = [[SearchView alloc]initWithFrame:CGRectMake(0, 0,kScreenWidth, 200)];
            
            __weak typeof(self)weakself = self;
            self.headerView.headerBlock = ^(NSDictionary *hdic, NSInteger index) {
                weakself.datasource = [NSMutableArray array];
                weakself.index = 1;
                weakself.searchStr = [NSString stringWithFormat:@"%@",hdic[@"NAME"]];
                NSString *urlstr = [NSString stringWithFormat:@"/dashop/goods/app/list.do?keywords=%@&CurrentPage=%ld",weakself
                                    .searchStr,weakself.index];
                NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:urlstr];
                NSString  *newUrlString = [endstr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
                [weakself SearchShopMethodWithUrl:newUrlString];
            };
            self.headerView.backgroundColor = [UIColor whiteColor];
            self.headerView.dataArray = self.contentArray;
            [self.view addSubview:self.headerView];
        }];
    } failBlock:^(NSError *error) {
        
    }];
    
}

-(void)creatSearchHeaderView{
    self.backHdview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, 50*kJLXWidthScale)];
    UIButton *btn = [UIButton buttonWithType:UIButtonTypeCustom];
    [btn setImage:[UIImage imageNamed:@"search.png"] forState:UIControlStateNormal];
    [btn addTarget:self action:@selector(searchButtonAction:) forControlEvents:UIControlEventTouchUpInside];
    [self.backHdview addSubview:btn];
    btn.sd_layout
    .centerYEqualToView(self.backHdview)
    .rightSpaceToView(self.backHdview, 8*kJLXWidthScale)
    .heightIs(25*kJLXWidthScale)
    .widthIs(25*kJLXWidthScale);
    UIView *fieldview = [UIView new];
    fieldview.layer.masksToBounds = YES;
    fieldview.layer.cornerRadius = 5*kJLXWidthScale;
    fieldview.layer.borderColor = LineBackColor.CGColor;
    fieldview.layer.borderWidth = 1;
    [self.backHdview addSubview:fieldview];
    fieldview.sd_layout
    .centerYEqualToView(self.backHdview)
    .leftSpaceToView(self.backHdview, 8*kJLXWidthScale)
    .rightSpaceToView(btn, 8*kJLXWidthScale)
    .heightIs(35*kJLXWidthScale);
    UITextField *field = [UITextField new];
    self.searchfield = field;
    field.placeholder = @"搜索商品";
    [fieldview addSubview:field];
    field.sd_layout
    .topSpaceToView(fieldview, 0)
    .bottomSpaceToView(fieldview, 0)
    .leftSpaceToView(fieldview, 5*kJLXWidthScale)
    .rightSpaceToView(fieldview, 5*kJLXWidthScale);
    [self.navigationItem.titleView sizeToFit];
    self.navigationItem.titleView = self.backHdview;
}

-(void)searchButtonAction:(UIButton *)sender{
    self.datasource = [NSMutableArray array];
    self.index = 1;
    self.searchStr = self.searchfield.text;
    NSString *urlstr = [NSString stringWithFormat:@"/dashop/goods/app/list.do?keywords=%@&CurrentPage=%ld",self
                        .searchStr,self.index];
    NSString *endstr = [MethodClass returnUrlSetStrWSDLURL:urlstr];
     NSString  *newUrlString = [endstr stringByAddingPercentEncodingWithAllowedCharacters:[NSCharacterSet URLQueryAllowedCharacterSet]];
    [self SearchShopMethodWithUrl:newUrlString];
}


-(void)SearchShopMethodWithUrl:(NSString *)url{
    [YQNetworking getWithUrl:url refreshRequest:YES cache:NO params:nil progressBlock:^(int64_t bytesRead, int64_t totalBytes) {
    } successBlock:^(id response) {
        NSArray *arr = response;
        self.page = arr.count;
        for (NSDictionary *dic in arr) {
            [self.datasource addObject:dic];
        }
        [[NSOperationQueue mainQueue]addOperationWithBlock:^{
//            self.headerView.hidden = YES;
//            self.listCollectionview.frame = CGRectMake(0, 0, kScreenWidth, kScreenHeight-64)
//            [self.listCollectionview reloadData];
            
            FirDetailController *detailVC = [[FirDetailController alloc]init];
            detailVC.navigationItem.title = self.searchStr;
            detailVC.imageArray = arr;
            [self.navigationController pushViewController:detailVC animated:YES];
            
        }];
    } failBlock:^(NSError *error) {
        
    }];
    
}


-(void)creatCollectionViewMethod{
    UICollectionViewFlowLayout *layout = [[UICollectionViewFlowLayout alloc]init];
    self.listCollectionview = [[UICollectionView alloc]initWithFrame:CGRectMake(0, 0, kScreenWidth, kScreenHeight-64) collectionViewLayout:layout];
  
    self.listCollectionview.backgroundColor = [UIColor whiteColor];
    self.listCollectionview.dataSource = self;
    self.listCollectionview.delegate = self;
    [self.listCollectionview registerClass:[UICollectionViewCell class] forCellWithReuseIdentifier:@"item"];
    [self.view addSubview:self.listCollectionview];
    
    
    
}


#pragma mark -- collertionView.dataSource
//返回item的个数
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section{
    return self.datasource.count;
    
    
}
//返回cell 对于每一item返回一个cell对象（重用机制）
- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath{
    UICollectionViewCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:@"item" forIndexPath:indexPath];
    [cell.contentView.subviews makeObjectsPerformSelector:@selector(removeFromSuperview)];
    NSDictionary *subdic = self.datasource[indexPath.row];
    NSString *urlstr = subdic[@"GOODS_PIC"];
    UIImageView *imagevi = [UIImageView new];
    NSURL *uRL = [NSURL URLWithString:[MethodClass returnUrlSetStrWSDLURL:urlstr]];
    [imagevi sd_setImageWithURL:uRL];
    [cell.contentView addSubview:imagevi];
    imagevi.sd_layout
    .topSpaceToView(cell.contentView, 15*kJLXWidthScale)
    .leftSpaceToView(cell.contentView, 25*kJLXWidthScale)
    .rightSpaceToView(cell.contentView, 25*kJLXWidthScale)
    .heightIs(cell.contentView.frame.size.height - 90*kJLXWidthScale);
    
    UILabel *titlab = [UILabel new];
    titlab.font = [UIFont systemFontOfSize:15*kJLXWidthScale];
    titlab.textAlignment = NSTextAlignmentCenter;
    titlab.textColor = [UIColor blackColor];
    titlab.numberOfLines = 3;
    titlab.text = [NSString stringWithFormat:@"%@",subdic[@"GOODS_NAME"]];
    [cell.contentView addSubview:titlab];
    titlab.sd_layout
    .topSpaceToView(imagevi, 0)
    .rightSpaceToView(cell.contentView, 10*kJLXWidthScale)
    .leftSpaceToView(cell.contentView, 10*kJLXWidthScale)
    .heightIs(60*kJLXWidthScale);
    
    UILabel *pricelab = [UILabel new];
    pricelab.font = [UIFont systemFontOfSize:16*kJLXWidthScale];
    pricelab.textAlignment = NSTextAlignmentLeft;
    pricelab.textColor = [UIColor orangeColor];
    pricelab.text = subdic[@"GOODS_MINPRICE"];
    [cell.contentView addSubview:pricelab];
    pricelab.sd_layout
    .topSpaceToView(titlab, 0)
    .rightSpaceToView(cell.contentView, 10*kJLXWidthScale)
    .leftSpaceToView(cell.contentView, 10*kJLXWidthScale)
    .heightIs(20*kJLXWidthScale);
    return cell;
}
//返回分区数
-(NSInteger)numberOfSectionsInCollectionView:(UICollectionView *)collectionView{
    return 1;
}

#pragma mark -- UICollectionViewDelegate
//点击item时
-(void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath{
    ShopDetailController *shopVC = [[ShopDetailController alloc]init];
    NSDictionary *dic = self.datasource[indexPath.row];
    NSString *urlstr = [NSString stringWithFormat:@"/dashop/goods/app/getGoods?GOODS_ID=%@&USER_ID=%@",dic[@"GOODS_ID"],[UserDefault objectForKey:LogUserID]];
    shopVC.urlStr = urlstr;
    shopVC.usdic = dic;
    [self.navigationController pushViewController:shopVC animated:YES];
}
//动态设置每个item的尺寸大小
- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout sizeForItemAtIndexPath:(NSIndexPath *)indexPath{
    return CGSizeMake(kScreenWidth/2 - 2, (kScreenWidth/2 - 2) + 70*kJLXWidthScale);
}
//最小行间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumLineSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}
//最小列间距
- (CGFloat)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout minimumInteritemSpacingForSectionAtIndex:(NSInteger)section{
    return 1;
}



////动态返回每个分区页脚的尺寸
//- (CGSize)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout*)collectionViewLayout referenceSizeForFooterInSection:(NSInteger)section{
//    return section == 0 ? CGSizeMake(100, 100) :CGSizeMake(200, 200);
//}
//动态设置item的缩进量
-(UIEdgeInsets)collectionView:(UICollectionView *)collectionView layout:(UICollectionViewLayout *)collectionViewLayout insetForSectionAtIndex:(NSInteger)section{
    return UIEdgeInsetsMake(10, 1, 0, 1);
    
}


@end
